package com.haogu.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haogu.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().append(new ObjectMapper().writeValueAsString(Result.failed("token不能为空")));
            return false;
        }
        Integer userId = (Integer) redisTemplate.opsForValue().get(token);
        if(userId == null){
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().append(new ObjectMapper().writeValueAsString(Result.failed("token失效了")));
            return false;
        }
        return true;
    }
}
